isProgramInstalled() {
	which "$1" > /dev/null 2>&1 && return 0
	return 1
}

# In-place editing like sed -i but more portable...
sed_i() {
	local cmd="$1"
	local file="$2"
	isProgramInstalled ed
	local addr=","
	echo "$cmd" | grep -qE '^/' && addr=
	ed -s "$file" > /dev/null 2>&1 << EOF
$addr$cmd
w
q
EOF
}

# Add $name=$value to the file, or modify an existing line if present in the file
setVsftpdValue() {
	local confFile="$1"
	local name="$2"
	local value="$3"
	local newLine="$name=$value"

	sed_i "s!^[ 	]*$name[ 	=:].*\$!$newLine!" "$confFile"
	grep -qE "^$newLine$" "$confFile" || echo "$newLine" >> "$confFile"
}

AddUser () {

local USERNAME=$1
local U1=${USERNAME:0:3}
local UU=`echo $U1 | tr "[:lower:]" "[:upper:]"`
local U2="/"${UU}"0"
local HOME="home"
local WWW="var/www"
local PARTITION=$2
local PASSWDDD=$3
local PARTITION_TYPE="/dev/sd"

useradd $USERNAME > /dev/null 2>> /tmp/install.log
echo "$USERNAME:$PASSWDDD" | chpasswd

usermod -d /$HOME/$USERNAME $USERNAME > /dev/null 2>> /tmp/install.log

mkdir /$HOME/$USERNAME > /dev/null 2>> /tmp/install.log

if [ -n $PARTITION ]
then 
mkfs.ext3 -m 0 $PARTITION_TYPE$PARTITION
cat >> /etc/fstab << OEF
$PARTITION_TYPE$PARTITION	/$HOME/$USERNAME	ext3	defaults	0	0
OEF
mount /$HOME/$USERNAME > /dev/null 2>> /tmp/install.log
fi

mkdir /$HOME/$USERNAME/watch > /dev/null 2>> /tmp/install.log
mkdir /$HOME/$USERNAME/torrents > /dev/null 2>> /tmp/install.log
mkdir /$HOME/$USERNAME/.session > /dev/null 2>> /tmp/install.log

cat > /$HOME/$USERNAME/.rtorrent.rc << OEF
schedule = chmod,0,0,"execute=chmod,777,/$HOME/$USERNAME/.session/$U1.socket"
execute = {sh,-c,rm -f /$HOME/$USERNAME/.session/$U1.socket}
scgi_local = /$HOME/$USERNAME/.session/$U1.socket
execute = {sh,-c,chmod 0666 /$HOME/$USERNAME/.session/$U1.socket}
encoding_list = UTF-8
port_range = 45000-65000
port_random = no
check_hash = no
directory = /$HOME/$USERNAME/torrents
session = /$HOME/$USERNAME/.session
encryption = allow_incoming, try_outgoing, enable_retry
schedule = watch_directory,1,1,"load_start=/$HOME/$USERNAME/watch/*.torrent"
schedule = untied_directory,5,5,"stop_untied=/$HOME/$USERNAME/watch/*.torrent"
use_udp_trackers = yes
dht = off
peer_exchange = no
execute = {sh,-c,/usr/bin/php /$WWW/rutorrent/php/initplugins.php $USERNAME &}
OEF

chown -R $USERNAME:$USERNAME /$HOME/$USERNAME > /dev/null 2>> /tmp/install.log

cat >> /etc/lighttpd/lighttpd.conf << OEF
"$U2" =>
( "127.0.0.1" =>
(
"socket" => "/$HOME/$USERNAME/.session/$U1.socket",
"check-local" => "disable",
"disable-time" => 0,  # don't disable scgi if connection fails
)
),
OEF

touch /etc/lighttpd/.auth

python /tmp/digest.py -u $USERNAME -p $PASSWDDD -r 'ruTorrent Seedbox' >> /etc/lighttpd/.auth

mkdir /$WWW/rutorrent/conf/users/$USERNAME > /dev/null 2>> /tmp/install.log

cat > /$WWW/rutorrent/conf/users/$USERNAME/config.php << OEF
<?php
\$topDirectory = '/$HOME/$USERNAME';
\$scgi_port = 0;
\$scgi_host = "unix:///$HOME/$USERNAME/.session/$U1.socket";
\$XMLRPCMountPoint = "$U2";
?>
OEF

cat > /etc/init.d/$U1.rtord << OEF
#!/bin/bash

### BEGIN INIT INFO
# Provides:                rtorrent
# Required-Start:       $remote_fs $syslog
# Required-Stop:       $remote_fs $syslog
# Default-Start:          2 3 4 5
# Default-Stop:          0 1 6
# Short-Description:  Start daemon at boot time
# Description:           Start-Stop rtorrent user session
### END INIT INFO

user="$USERNAME"

# the full path to the filename where you store your rtorrent configuration
config="/$HOME/$USERNAME/.rtorrent.rc"

# set of options to run with
options=""

# default directory for screen, needs to be an absolute path
base="/$HOME/$USERNAME"

# name of screen session
srnname="rtorrent"

# file to log to (makes for easier debugging if something goes wrong)
logfile="/var/log/rtorrentInit.log"
#######################
###END CONFIGURATION###
#######################
PATH=/usr/bin:/usr/local/bin:/usr/local/sbin:/sbin:/bin:/usr/sbin
DESC="rtorrent"
NAME=rtorrent
DAEMON=\$NAME
SCRIPTNAME=/etc/init.d/\$NAME

checkcnfg() {
    exists=0
    for i in \`echo "\$PATH" | tr ':' '\n'\` ; do
        if [ -f \$i/\$NAME ] ; then
            exists=1
            break
        fi
    done
    if [ \$exists -eq 0 ] ; then
        echo "cannot find rtorrent binary in PATH \$PATH" | tee -a "\$logfile" >&2
        exit 3
    fi
    if ! [ -r "\${config}" ] ; then
        echo "cannot find readable config \${config}. check that it is there and permissions are appropriate" | tee -a "\$logfile" >&2
        exit 3
    fi
    session=\`getsession "\$config"\`
    if ! [ -d "\${session}" ] ; then
        echo "cannot find readable session directory \${session} from config \${config}. check permissions" | tee -a "\$logfile" >&2
        exit 3

        fi

}

d_start() {

  [ -d "\${base}" ] && cd "\${base}"

  stty stop undef && stty start undef
  su -c "screen -ls | grep -sq "\.\${srnname}[[:space:]]" " \${user} || su -c "screen -dm -S \${srnname} 2>&1 1>/dev/null" \${user} | tee -a "\$logfile" >&2
  su -c "screen -S "\${srnname}" -X screen rtorrent \${options} 2>&1 1>/dev/null" \${user} | tee -a "\$logfile" >&2
}

d_stop() {
    session=\`getsession "\$config"\`
    if ! [ -s \${session}/rtorrent.lock ] ; then
        return
    fi
    pid=\`cat \${session}/rtorrent.lock | awk -F: '{print(\$2)}' | sed "s/[^0-9]//g"\`
    if ps -A | grep -sq \${pid}.*rtorrent ; then # make sure the pid doesn't belong to another process
        kill -s INT \${pid}
    fi
}

getsession() {
    session=\`cat "\$1" | grep "^[[:space:]]*session[[:space:]]*=" | sed "s/^[[:space:]]*session[[:space:]]*=[[:space:]]*//" \`
    echo \$session
}

checkcnfg

case "\$1" in
  start)
    echo -n "Starting \$DESC: \$NAME"
    d_start
    echo "."
    ;;
  stop)
    echo -n "Stopping \$DESC: \$NAME"
    d_stop
    echo "."
    ;;
  restart|force-reload)
    echo -n "Restarting \$DESC: \$NAME"
    d_stop
    sleep 1
    d_start
    echo "."
    ;;
  *)
    echo "Usage: \$SCRIPTNAME {start|stop|restart|force-reload}" >&2
    exit 1
    ;;
esac

exit 0
OEF

chmod +x /etc/init.d/$U1.rtord

update-rc.d $U1.rtord defaults > /dev/null 2>> /tmp/install.log

chown root:$USERNAME /$HOME/$USERNAME
chmod 755 /$HOME/$USERNAME

cat >> /etc/ssh/sshd_config << OEF
Match user $USERNAME
         ChrootDirectory /$HOME/$USERNAME
OEF

crontab -l > /tmp/mycron
echo "*/1 * * * * if ! ( ps -U $USERNAME | grep rtorrent > /dev/null ); then /etc/init.d/$U1.rtord start; fi" >> /tmp/mycron
crontab /tmp/mycron
rm /tmp/mycron
}

echo -n "Nombre d'utilisateur(s) : "
read NBUTIL
i=0
while [ $i -lt $NBUTIL ] ; do
let NUMUTIL=i+1
read -p "Utilisateur #$NUMUTIL : " USER[$i]
read -p "Mot de passe #$NUMUTIL : " PASS[$i]
read -p "Partition #$NUMUTIL : " PART[$i]
let i++
done

echo "Suppression des paquets inutiles"
if isProgramInstalled bind9 ; then
/etc/init.d/bind9 stop > /dev/null 2>> /tmp/install.log
update-rc.d -f bind9 remove > /dev/null 2>> /tmp/install.log
aptitude purge -y bind9 > /dev/null 2>> /tmp/install.log
fi
echo "Fait."

echo "Installation des paquets"

cat >>  /etc/apt/sources.list <<EOF

deb http://ftp2.fr.debian.org/debian/ squeeze main non-free
deb-src http://ftp2.fr.debian.org/debian/ squeeze main non-free
EOF

aptitude update > /dev/null 2>> /tmp/install.log
aptitude safe-upgrade -y -q

aptitude install -y -q ffmpeg htop rar zip build-essential pkg-config libcurl4-openssl-dev libsigc++-2.0-dev libncurses5-dev lighttpd nano screen subversion libterm-readline-gnu-perl php5-cgi apache2-utils libcurl3 curl php5-curl php5-cli dtach unzip unrar > /dev/null 2>> /tmp/install.log
echo "Fait."

echo "Installation de libtorrent"
cd /tmp > /dev/null 2>> /tmp/install.log
wget http://libtorrent.rakshasa.no/downloads/libtorrent-0.12.9.tar.gz > /dev/null 2>> /tmp/install.log
tar zxfv libtorrent-0.12.9.tar.gz > /dev/null 2>> /tmp/install.log
cd libtorrent-0.12.9 > /dev/null 2>> /tmp/install.log
./configure > /dev/null 2>> /tmp/install.log
make > /dev/null 2>> /tmp/install.log
make install > /dev/null 2>> /tmp/install.log
cd /tmp > /dev/null 2>> /tmp/install.log
rm -R libtorrent-0.12.9 libtorrent-0.12.9.tar.gz > /dev/null 2>> /tmp/install.log

echo "Installation de xmlrpc-c"
cd /tmp > /dev/null 2>> /tmp/install.log
svn checkout http://xmlrpc-c.svn.sourceforge.net/svnroot/xmlrpc-c/stable xmlrpc-c > /dev/null 2>> /tmp/install.log
cd xmlrpc-c/ > /dev/null 2>> /tmp/install.log
./configure > /dev/null 2>> /tmp/install.log
make > /dev/null 2>> /tmp/install.log
make install > /dev/null 2>> /tmp/install.log
cd /tmp > /dev/null 2>> /tmp/install.log
rm -R xmlrpc-c > /dev/null 2>> /tmp/install.log

echo "Installation de rtorrent"
cd /tmp > /dev/null 2>> /tmp/install.log
wget http://libtorrent.rakshasa.no/downloads/rtorrent-0.8.9.tar.gz > /dev/null 2>> /tmp/install.log
tar zxfv rtorrent-0.8.9.tar.gz > /dev/null 2>> /tmp/install.log
cd rtorrent-0.8.9 > /dev/null 2>> /tmp/install.log
./configure --with-xmlrpc-c > /dev/null 2>> /tmp/install.log
make > /dev/null 2>> /tmp/install.log
make install > /dev/null 2>> /tmp/install.log
cd /tmp > /dev/null 2>> /tmp/install.log
rm -R rtorrent-0.8.9 rtorrent-0.8.9.tar.gz > /dev/null 2>> /tmp/install.log
if isProgramInstalled rtorrent
     then echo "OK."
	 else echo "Installation de rtorrent a échouée. Essayez manuellement."
fi

echo "Installation de rutorrent"
cd /var/www/ > /dev/null 2>> /tmp/install.log
svn checkout http://rutorrent.googlecode.com/svn/trunk/rutorrent/ > /dev/null 2>> /tmp/install.log
cd rutorrent > /dev/null 2>> /tmp/install.log
rm -R plugins > /dev/null 2>> /tmp/install.log
svn checkout http://rutorrent.googlecode.com/svn/trunk/plugins/ > /dev/null 2>> /tmp/install.log
cd /var/www/rutorrent/plugins/ > /dev/null 2>> /tmp/install.log
svn co http://rutorrent-chat.googlecode.com/svn/trunk/ chat > /dev/null 2>> /tmp/install.log
cd /var/www/rutorrent/plugins/ > /dev/null 2>> /tmp/install.log
svn co http://rutorrent-logoff.googlecode.com/svn/trunk/ logoff > /dev/null 2>> /tmp/install.log
cd /var/www/rutorrent/plugins/ > /dev/null 2>> /tmp/install.log
svn co http://rutorrent-pausewebui.googlecode.com/svn/trunk/ pausewebui > /dev/null 2>> /tmp/install.log
cd /var/www/rutorrent/plugins/ > /dev/null 2>> /tmp/install.log
wget http://rutorrent-tadd-labels.googlecode.com/files/lbll-suite_0.8.1.tar.gz > /dev/null 2>> /tmp/install.log
tar zxfv lbll-suite_0.8.1.tar.gz > /dev/null 2>> /tmp/install.log
rm lbll-suite_0.8.1.tar.gz > /dev/null 2>> /tmp/install.log
cd /var/www/rutorrent/plugins/ > /dev/null 2>> /tmp/install.log
svn co http://svn.rutorrent.org/svn/filemanager/trunk/filemanager > /dev/null 2>> /tmp/install.log

echo "Installation de buildtorrent"
cd /tmp > /dev/null 2>> /tmp/install.log
wget http://claudiusmaximus.goto10.org/files/coding/buildtorrent/buildtorrent-0.8.tar.gz > /dev/null 2>> /tmp/install.log
tar -xzvf buildtorrent-0.8.tar.gz > /dev/null 2>> /tmp/install.log
cd buildtorrent-0.8 > /dev/null 2>> /tmp/install.log
./configure > /dev/null 2>> /tmp/install.log
make > /dev/null 2>> /tmp/install.log
make install > /dev/null 2>> /tmp/install.log
cd /tmp > /dev/null 2>> /tmp/install.log
rm -R buildtorrent-0.8 buildtorrent-0.8.tar.gz > /dev/null 2>> /tmp/install.log


echo "Installation de mediainfo"
MACHINE_TYPE=`uname -m`
if [ ${MACHINE_TYPE} == 'x86_64' ]; then
  ARCH="amd64"
else
  ARCH="i386"
fi
cd /tmp > /dev/null 2>> /tmp/install.log
wget http://downloads.sourceforge.net/zenlib/libzen0_0.4.17-1_$ARCH.Debian_5.deb > /dev/null 2>> /tmp/install.log
dpkg -i libzen0_0.4.17-1_$ARCH.Debian_5.deb > /dev/null 2>> /tmp/install.log
wget http://downloads.sourceforge.net/mediainfo/libmediainfo0_0.7.39-1_$ARCH.Debian_5.deb > /dev/null 2>> /tmp/install.log
dpkg -i libmediainfo0_0.7.39-1_$ARCH.Debian_5.deb > /dev/null 2>> /tmp/install.log
wget http://downloads.sourceforge.net/mediainfo/mediainfo_0.7.39-1_$ARCH.Debian_5.deb > /dev/null 2>> /tmp/install.log
dpkg -i mediainfo_0.7.39-1_$ARCH.Debian_5.deb > /dev/null 2>> /tmp/install.log
rm libzen0_0.4.17-1_$ARCH.Debian_5.deb libmediainfo0_0.7.39-1_$ARCH.Debian_5.deb mediainfo_0.7.39-1_$ARCH.Debian_5.deb > /dev/null 2>> /tmp/install.log

ldconfig > /dev/null 2>> /tmp/install.log
chown -R www-data:www-data /var/www/rutorrent > /dev/null 2>> /tmp/install.log

echo "Configuration"

cat >> /var/www/rutorrent/conf/plugins.ini << OEF
;; Pas forcement utile

[scheduler]
enabled = no
[rpc]
enabled = no
[retrackers]
enabled = no
[httprpc]
enabled = no
[geoip]
enabled = no
OEF

#Configuration du plugin create
rm /var/www/rutorrent/plugins/create/conf.php > /dev/null 2>> /tmp/install.log

cat > /var/www/rutorrent/plugins/create/conf.php <<OEF
<?php
        // configuration parameters

        @define('MAX_CONSOLE_SIZE',25,true);

        \$useExternal = "buildtorrent";
        \$pathToCreatetorrent = '/usr/local/bin/buildtorrent';              // Something like /bin/createtorrent, or /bin/transmissioncli. If empty, program will be founded in PATH.
        \$pathToExternals["pgrep"] = '';         // Something like /usr/bin/pgrep. If empty, will be founded in PATH.

?>
OEF

mv /var/www/rutorrent/plugins/filemanager/conf.php /var/www/rutorrent/plugins/filemanager/conf.php.bak
sed 's/\/usr\/bin\/rar'

#Configuration du serveur web
#On modifie le fichier /etc/lighttpd/lighttpd.conf
cat >> /etc/lighttpd/lighttpd.conf << OEF
fastcgi.server = ( ".php" => ((
                     "bin-path" => "/usr/bin/php5-cgi",
                     "socket" => "/tmp/php.socket"
                 )))
\$SERVER["socket"] == ":443" {
ssl.engine = "enable"
ssl.pemfile = "/etc/lighttpd/certs/lighttpd.pem"
}
server.modules += ( "mod_auth" )
auth.backend = "htdigest"
auth.backend.htdigest.userfile = "/etc/lighttpd/.auth"
auth.debug = 2
auth.require = ( "/rutorrent/" =>
(
"method" => "digest",
"realm" => "ruTorrent Seedbox",
"require" => "valid-user"
)
)
server.modules += ( "mod_scgi" )
scgi.server = (
OEF

echo "On active le module fastcgi en fonction de php"
if [ -e /etc/lighttpd/conf-available/10-fastcgi-php5.conf ]; then
/usr/sbin/lighty-enable-mod fastcgi-php5 > /dev/null 2>> /tmp/install.log
else
/usr/sbin/lighty-enable-mod fastcgi > /dev/null 2>> /tmp/install.log
fi

mkdir /etc/lighttpd/certs > /dev/null 2>> /tmp/install.log
cd /etc/lighttpd/certs > /dev/null 2>> /tmp/install.log
openssl req -new -newkey rsa:1024 -days 365 -nodes -x509 -keyout lighttpd.pem -out lighttpd.pem -batch > /dev/null 2>> /tmp/install.log

/etc/init.d/lighttpd force-reload > /dev/null 2>> /tmp/install.log

aptitude install -y vsftpd > /dev/null 2>> /tmp/install.log

confFile="/etc/vsftpd.conf"
touch "$confFile"
setVsftpdValue "$confFile" anonymous_enable NO
setVsftpdValue "$confFile" dirlist_enable YES
setVsftpdValue "$confFile" download_enable YES
setVsftpdValue "$confFile" guest_enable NO
setVsftpdValue "$confFile" listen YES
setVsftpdValue "$confFile" listen_ipv6 NO
setVsftpdValue "$confFile" local_enable YES
setVsftpdValue "$confFile" local_umask 022
setVsftpdValue "$confFile" max_per_ip 0
setVsftpdValue "$confFile" pasv_enable YES
setVsftpdValue "$confFile" port_enable YES
setVsftpdValue "$confFile" pasv_promiscuous NO
setVsftpdValue "$confFile" port_promiscuous NO
setVsftpdValue "$confFile" pasv_min_port 0
setVsftpdValue "$confFile" pasv_max_port 0
setVsftpdValue "$confFile" write_enable YES
setVsftpdValue "$confFile" chroot_local_user YES
setVsftpdValue "$confFile" chroot_list_enable YES
setVsftpdValue "$confFile" chroot_list_file /etc/vsftpd.chroot_list

touch /etc/vsftpd.chroot_list > /dev/null 2>> /tmp/install.log

/etc/init.d/vsftpd reload > /dev/null 2>> /tmp/install.log

cd /tmp > /dev/null 2>> /tmp/install.log
wget http://images.mondedie.fr/images/digest.py > /dev/null 2>> /tmp/install.log

j=0
while [ $j -lt $NBUTIL ] ; do
AddUser "${USER[$j]}" "${PART[$j]}" "${PASS[$j]}"
let j++
done

cat >> /etc/lighttpd/lighttpd.conf << OEF
)
OEF

/etc/init.d/lighttpd restart > /dev/null 2>> /tmp/install.log

#nano /etc/ssh/sshd_config
#Subsystem sftp internal-sftp
#/etc/init.d/ssh restart

